package bizlogic;

import java.sql.SQLException;

import model.UserDTO;
import dao.DAOException;
import dao.DAOFactory;
import dao.UserDAO;

public class UserManager {

	private UserDAO userDAO = null;

	public UserManager() {
		userDAO = DAOFactory.loadInstance().getUserDAO();
	}


	public UserDTO[] findAllUsers()  {
		UserDTO[] users = new UserDTO[1];
		try {
			users = userDAO.getAllUsers();
		} catch (DAOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return users;
	}
	
	public UserDTO[] findAllManagers()  {
		UserDTO[] users = new UserDTO[1];
		try {
			users = userDAO.getAllManagers();
		} catch (DAOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return users;
	}
	
	public UserDTO getUserDetail(String userId){
		UserDTO user = new UserDTO();
		try {
			user = userDAO.getUser(userId);
		} catch (DAOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

	public void updateUser(UserDTO user) {
		try {
			userDAO.updateUser(user);
		} catch (DAOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void createUser(UserDTO user){
		try {
			userDAO.insertUser(user);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void deleteUser(String username) {
		try {
			userDAO.deleteUser(username);
		} catch (DAOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isLoginDetailsValid(UserDTO userToCheck)
	{	
		UserDTO userDB = new UserDTO();		
		
		try{
			userDB = userDAO.getUser(userToCheck.getUsername());
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if(userDB.getPassword() == null || userDB.getPassword() == null){
			return false;
		}
		else if(!userDB.getPassword().matches(userToCheck.getPassword())){
			return false;
		}else{
			userToCheck = userDB;
			return true;
		}
	}
}